<template>
  <div>
    <div>
      <div style="width:calc(50% - 10px);height:30%;float:left;margin:0px 0px 50px 0px">
        <!--        <span>原车主车辆</span>-->
        <BreakSpace label="原车主车辆" :containerStyle="{ marginBottom: '10px' }" />
        <FormPanel ref="formPanel" :list="formList" :cols="1" :labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
      </div>
      <div style="width:50%;height:30%;float:right;">
        <!--        <span>新车主</span> -->
        <BreakSpace label="新车主" :containerStyle="{ marginBottom: '10px' }" />
        <FormPanel ref="formPanel_new" :list="formList_new" :cols="1" :labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle_new" />
      </div>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: '200px',
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <!-- <el-checkbox v-model="isSyncRepairHistory">是否同步维修历史</el-checkbox> -->
      <AjaxButton type="primary" :click="saveDrawer">过 户</AjaxButton>
      <el-button @click="closeDrawer">关 闭</el-button>
    </div>
    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose width="70%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryVehiclePanel :parms="this.parms" @close="closeDialog" @vehicleData="vehicleData" />
    </BaseDialog>
    <BaseDialog :visible.sync="visible_new" :title="dialogTitle_new" destroyOnClose width="70%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <queryOwnerPanel :parms="this.parms_new" @close="closeDialog_new" @ownerData="ownerData" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import queryVehiclePanel from './queryVehiclePanel';
import queryOwnerPanel from './queryOwnerPanel';
import { getAppId } from '@/assets/js/auth';
import { saveVehicleChange } from '@/api/customerRepair/vehicleOwnerManagement/vehicleChange';
import { getPinpSelect, getChexSelect, getCheModelSelect } from '@/api/repair/repairReception/customer/brand.js';
import { notifyAction, isFormEmpty } from '@/utils';
export default {
  name: 'vehicleTransferOwnership',
  components: {
    queryVehiclePanel,
    queryOwnerPanel
  },
  mixins: [dictionary],
  props: {
    type: {
      type: String
    },
    formData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.saveData = {};
    this.saveData_new = {};
    this.parms = {};
    this.parms_new = {};
    return {
      visible: false,
      visible_new: false,
      dialogTitle: '',
      dialogTitle_new: '',
      isSyncRepairHistory: '',
      formList: this.createFormList(),
      formList_new: this.createFormList_new()
    };
  },
  computed: {},
  created() {
    this.getBrand();
  },
  mounted() {
    this.initialHandle();
  },
  methods: {
    initialHandle() {
      if (this.type === 'edit') {
        this.formList.forEach(x => {
          x.initialValue = this.formData[x.fieldName];
          if (x.fieldName === 'vin1') {
            x.initialValue = this.findFormItem('vin').initialValue;
          }
          if (x.fieldName === 'brand') {
            this.getSeries(x.initialValue);
          }
          if (x.fieldName === 'series') {
            this.getModel(this.findFormItem('brand').initialValue, x.initialValue);
          }
          if (x.fieldName === 'ownerNo') {
            x.initialValue = this.formData['ownerNoOld'];
          }
          if (x.fieldName === 'certificateNo') {
            x.initialValue = this.formData['oldCertificateNo'];
          }
        });
        this.formList_new.forEach(x => {
          x.initialValue = this.formData[x.fieldName];
          if (x.fieldName === 'newBrand') {
            this.getSeries(x.initialValue);
          }
          if (x.fieldName === 'newSeries') {
            this.getModel(this.findFormItemNew('newBrand').initialValue, x.initialValue);
          }
          if (x.fieldName === 'newOwnerNo') {
            x.initialValue = this.formData['ownerNoNew'];
          }
          if (x.fieldName === 'identityUpload') {
            let files = [];
            let url = !isFormEmpty(this.formData['idEnclosureUrl']) ? this.formData['idEnclosureUrl'].split(',') : [];
            let name = !isFormEmpty(this.formData['idEnclosureName']) ? this.formData['idEnclosureName'].split(',') : [];
            if (url !== [] && name !== []) {
              for (let i = 0; i < url.length; i++) {
                if (i <= name.length) {
                  files.push({ url: url[i], name: name[i] });
                }
              }
            }
            x.initialValue = files;
          }
          if (x.fieldName === 'drivingFileUpload') {
            let files = [];
            let url = !isFormEmpty(this.formData['drivingEnclosureUrl']) ? this.formData['drivingEnclosureUrl'].split(',') : [];
            let name = !isFormEmpty(this.formData['drivingEnclosureName']) ? this.formData['drivingEnclosureName'].split(',') : [];
            if (url !== [] && name !== []) {
              for (let i = 0; i < url.length; i++) {
                if (i <= name.length) {
                  files.push({ url: url[i], name: name[i] });
                }
              }
            }
            x.initialValue = files;
          }
        });
        if (this.formData['powerType'] == '60081002') {
          this.formList.find(x => x.fieldName == 'engineNo').label = '电机号';
          this.formList_new.find(x => x.fieldName == 'newEngineNo').label = '电机号';
        }
      }
      let appId = getAppId();
      if (appId == 'arcfox') {
        this.formList.find(x => x.fieldName == 'engineNo').label = '电机号';
        this.formList_new.find(x => x.fieldName == 'newEngineNo').label = '电机号';
      }
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          readonly: true,
          disabled: this.type === 'edit' ? true : false,
          initialValue: '',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.openVehicle}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主编号',
          fieldName: 'ownerNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主身份证号',
          fieldName: 'certificateNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin1',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'engineNo',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          itemList: [],
          change: val => {
            this.changePinpSelect(val);
          },
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          itemList: [],
          change: val => {
            this.changeChexSelect(val);
          },
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          // rules: [
          //   {
          //     required: true,
          //     pattern: /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
          //     message: '请输入正确的车牌号'
          //   }
          // ],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主地址',
          fieldName: 'address',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '电话',
          fieldName: 'phone',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '手机',
          fieldName: 'mobile',
          disabled: true
        }
      ];
    },
    createFormList_new() {
      return [
        {
          type: 'INPUT',
          label: '新车主',
          fieldName: 'newOwnerName',
          readonly: true,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={this.queryOwner} />;
          }
          // onEnter: val => {
          //   this.queryOwner(val);
          // }
        },
        {
          type: 'INPUT',
          label: '车主编号',
          fieldName: 'newOwnerNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主身份证号',
          fieldName: 'newCertificateNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'newVin',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '发动机号',
          fieldName: 'newEngineNo',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'newBrand',
          itemList: [],
          change: val => {
            this.changePinpSelect(val);
          },
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'newSeries',
          itemList: [],
          change: val => {
            this.changeChexSelect(val);
          },
          disabled: true
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'newModel',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'newLicense',
          // rules: [
          //   {
          //     required: true,
          //     pattern: /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
          //     message: '请输入正确的车牌号'
          //   }
          // ],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主地址',
          fieldName: 'newAddress',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '电话',
          fieldName: 'newPhone',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '手机',
          fieldName: 'newMobile',
          disabled: true
        },

        {
          type: 'SELECT',
          label: '保险是否过户',
          fieldName: 'isTransfer',
          itemList: this.createDictList(1004),
          initialValue: 10041001
        },
        {
          type: 'UPLOAD_FILE',
          label: '身份证附件',
          fieldName: 'identityUpload',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            fileTypes: ['pdf', 'jpg', 'png', 'bmp', 'pdf', 'doc', 'docx'],
            max: 1024 * 100,
            limit: 2
          },
          initialValue: '',
          disabled: false,
          selfCols: 2,
          rules: [{ required: true, message: '请上传身份证附件', trigger: 'blur' }]
        },
        {
          type: 'UPLOAD_FILE',
          label: '行驶证附件',
          fieldName: 'drivingFileUpload',
          upload: {
            actionUrl: '/api/file/oss/upload', //上传的地址
            fileTypes: ['pdf', 'jpg', 'png', 'bmp', 'pdf', 'doc', 'docx'],
            max: 1024 * 100,
            limit: 2
          },
          initialValue: '',
          disabled: false,
          selfCols: 2,
          rules: [{ required: true, message: '请上传行驶证附件', trigger: 'blur' }]
        }
      ];
    },
    // 取原车主表单值通用方法
    findFormItem(fieldName) {
      return this.formList.find(x => x.fieldName === fieldName) || {};
    },
    // 取新车主表单通用方法
    findFormItemNew(fieldName) {
      return this.formList_new.find(x => x.fieldName === fieldName) || {};
    },
    queryOwner(val) {
      this.dialogTitle_new = '选择车主';
      this.visible_new = true;
    },
    openVehicle() {
      this.dialogTitle = 'VIN选择';
      this.visible = true;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    formChangeHandle_new(val) {
      this.saveData_new = val;
    },
    async saveDrawer() {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      const [errNew, dataNew] = await this.$refs.formPanel_new.GET_FORM_DATA();
      if (errNew) return;
      // 调用后台保存保存前判断
      if (data.ownerName == undefined || dataNew.newOwnerName == undefined) {
        notifyAction('原车主与新车主存在空值,不能进行过户操作！', 'warning');
      } else {
        if (data.ownerNo == dataNew.newOwnerNo) {
          notifyAction('原车主与新车主相同,不能进行过户操作！', 'warning');
        } else {
          if (this.type === 'edit') {
            data.vehicleTransferId = this.formData.vehicleTransferId;
          }
          const res = await saveVehicleChange({ ...data, ...dataNew });
          if (res.resultCode === 200) {
            if (res.errMsg) {
              notifyAction(res.errMsg, 'error');
            } else {
              notifyAction('车辆过户成功！');
            }
            this.$emit('close', true);
          }
        }
      }
    },
    // 回写新车主数据
    ownerData(val) {
      // 客户编号
      this.findFormItemNew('newOwnerNo').initialValue = val['ownerNo'];
      // 客户身份证号
      this.findFormItemNew('newCertificateNo').initialValue = val['certificateNo'];
      // 客户姓名
      this.findFormItemNew('newOwnerName').initialValue = val['ownerName'];
      // 客户编号
      // 客户身份证号
      // 手机
      this.findFormItemNew('newMobile').initialValue = val['mobile'];
      // 电话
      this.findFormItemNew('newPhone').initialValue = val['phone'];
      // 地址
      this.findFormItemNew('newAddress').initialValue = val['address'];

      this.closeDialog_new(false);
    },
    // 回写原车辆数据
    vehicleData(val) {
      this.formList.forEach(x => {
        x.initialValue = val[x.fieldName];
        if (x.fieldName === 'vin1') {
          this.findFormItem('vin1').initialValue = val['vin'];
        }
        if (x.fieldName === 'engineNo' && val['powerType'] == '60081002') {
          this.findFormItem('engineNo').initialValue = val['motorNo'];
        }
      });
      // 车牌号
      this.findFormItemNew('newLicense').initialValue = val['license'];
      // VIN
      this.findFormItemNew('newVin').initialValue = val['vin'];
      // 发动机号
      if (val['powerType'] == '60081002') {
        this.findFormItemNew('newEngineNo').initialValue = val['motorNo'];
        this.findFormItemNew('newEngineNo').label = '电机号';
        this.findFormItem('engineNo').label = '电机号';
      } else {
        this.findFormItemNew('newEngineNo').initialValue = val['engineNo'];
      }
      // 品牌
      if (val['brand']) {
        this.findFormItemNew('newBrand').initialValue = this.findFormItem('brand').initialValue = val['brand'];
      }
      // 车系
      if (val['series']) {
        this.getSeries(this.findFormItem('brand').initialValue);
        this.findFormItemNew('newSeries').initialValue = this.findFormItem('series').initialValue = val['series'];
      }
      // 车型
      if (val['model']) {
        this.getModel(this.findFormItem('brand').initialValue, this.findFormItem('series').initialValue);
        this.findFormItemNew('newModel').initialValue = this.findFormItem('model').initialValue = val['model'];
      }
      this.closeDialog(false);
    },
    closeDialog(val) {
      this.visible = val;
    },
    closeDialog_new(val) {
      this.visible_new = val;
    },
    closeDrawer() {
      this.$emit('close', false, 'refresh');
    },
    // 品牌
    async getBrand() {
      const res = await getPinpSelect();
      this.formList.find(item => item.fieldName === 'brand').itemList = this.formList_new.find(item => item.fieldName === 'newBrand').itemList = res.data.map(x => ({
        value: x.brandId + '',
        text: x.brandName
      }));
    },
    // 车系
    async getSeries(brandsid) {
      const res = await getChexSelect(brandsid);
      this.formList.find(item => item.fieldName === 'series').itemList = this.formList_new.find(item => item.fieldName === 'newSeries').itemList = res.data.map(x => ({
        value: x.seriesId + '',
        text: x.seriesName
      }));
    },
    // 车型
    async getModel(brandsid, seriessid) {
      const res = await getCheModelSelect(brandsid, seriessid);
      this.formList.find(item => item.fieldName === 'model').itemList = this.formList_new.find(item => item.fieldName === 'newModel').itemList = res.data.map(x => ({
        value: x.modelId + '',
        text: x.modelName
      }));
    }
  }
};
</script>

<style lang="less" scoped></style>
